import VipPopup from '@/components/VipPopup/VipPopup';
import { getOrderList } from '@/servers/api/order';
import { getUserAuthIcon } from '@/servers/api/userController';
import { customFormat } from '@/utils';
import { FormattedMessage, history, useIntl, useModel } from '@umijs/max';
import {
    Button,
    Col,
    Form,
    Modal,
    Row,
    Select,
    Space,
    Spin,
    Table,
} from 'antd';
import dayjs from 'dayjs';
import { useEffect, useRef, useState } from 'react';

const Order: React.FC = () => {
    const intl = useIntl();
    const { initialState } = useModel('@@initialState');
    const { authModal } = useModel('useUser');
    const [isModalOpen, setIsModalOpen] = useState(false);
    const [form] = Form.useForm();
    const [formModal] = Form.useForm();
    const [dataSource, setdataSource] = useState([]); //表格
    const [pageLoading, setpageLoading] = useState(false);
    const currentOptions = [
        //分类
        {
            value: 0,
            label: <FormattedMessage id="已发布"></FormattedMessage>,
        },
        {
            value: 1,
            label: <FormattedMessage id="已参与"></FormattedMessage>,
        },
        {
            value: 2,
            label: <FormattedMessage id="进行中"></FormattedMessage>,
        },
        {
            value: 3,
            label: <FormattedMessage id="已完成"></FormattedMessage>,
        },
    ];
    const options1 = [
        {
            label: <FormattedMessage id="货物"></FormattedMessage>,
            label_ru: <FormattedMessage id="货物"></FormattedMessage>,
            value: 'goods',
        },
        {
            label: <FormattedMessage id="运输"></FormattedMessage>,
            label_ru: <FormattedMessage id="运输"></FormattedMessage>,
            value: 'transport',
        },
        {
            label: <FormattedMessage id="跨境货代"></FormattedMessage>,
            label_ru: <FormattedMessage id="跨境货代"></FormattedMessage>,
            value: 'crossborder',
        },
        {
            label: <FormattedMessage id="专业代办"></FormattedMessage>,
            label_ru: <FormattedMessage id="专业代办"></FormattedMessage>,
            value: 'professional',
        },
    ];
    const options2 = [
        {
            label: <FormattedMessage id="不限"></FormattedMessage>,
            label_ru: <FormattedMessage id="不限"></FormattedMessage>,
            value: '',
        },
        {
            label: <FormattedMessage id="近三天"></FormattedMessage>,
            label_ru: <FormattedMessage id="近三天"></FormattedMessage>,
            value: 3,
        },
        {
            label: <FormattedMessage id="近五天"></FormattedMessage>,
            label_ru: <FormattedMessage id="近五天"></FormattedMessage>,
            value: 5,
        },
        {
            label: <FormattedMessage id="近七天"></FormattedMessage>,
            label_ru: <FormattedMessage id="近七天"></FormattedMessage>,
            value: 7,
        },
    ];
    const listUrl = {
        goods1: '/releasegoods',
        transport1: '/releasetransport',
        crossborder1: '/releasecrossborder',
        professional1: '/releaseprofessional',
        lifead1: '/releaselifead',
        news1: '/releasenews',
        exposure1: '/releaseexposure',
        goods2: '/releasegoods',
        transport2: '/releasetransport',
        crossborder2: '/releasecrossborder',
        professional2: '/releaseprofessional',
        lifead2: '/releaselifead',
        news2: '/releasenews',
        exposure2: '/releaseexposure',
    };
    //详情
    function details(row) {
        history.push('/published', {
            id: row.id,
            status: form.getFieldValue('status'),
        });
    }
    function goRatie(id: string) {
        history.push('/takepart', {
            order_id: id,
            type: 'join',
        });
    }
    const [columns, setcolumns] = useState<Array<any>>();
    const [allData, setAllData] = useState<Array<any>>();
    const baseBtn = [
        {
            title: <FormattedMessage id="操作"></FormattedMessage>,
            key: 'action',
            render: (text, record) => (
                <Space size="middle">
                    {form.getFieldValue('status') === 1 && (
                        <Button
                            type="primary"
                            size="small"
                            onClick={() => {
                                details(record);
                            }}
                        >
                            <FormattedMessage id="修改参与信息"></FormattedMessage>
                        </Button>
                    )}
                    <Button
                        type="primary"
                        ghost
                        size="small"
                        onClick={() => {
                            details(record);
                        }}
                    >
                        <FormattedMessage id="查看详情"></FormattedMessage>
                    </Button>
                    {form.getFieldValue('status') === 3 && (
                        <Button
                            className="warning"
                            ghost
                            size="small"
                            onClick={() => {
                                goRatie(record.id);
                            }}
                        >
                            <FormattedMessage id="查看评价"></FormattedMessage>
                        </Button>
                    )}
                </Space>
            ),
        },
    ];
    const [tableparams, settableparams] = useState({
        page: 1,
        size: 10,
        status: 0,
        search: '',
        search1: 'goods',
    });
    /* 计算表头 */
    function compCol() {
        switch (form.getFieldValue('search1')) {
            case 'goods':
                setcolumns([
                    {
                        title: (
                            <FormattedMessage id="订单编号"></FormattedMessage>
                        ),
                        key: 'order_no',
                        render: (text: string, record) => (
                            <>{record.order_no}</>
                        ),
                    },
                    {
                        title: (
                            <FormattedMessage id="货物名称"></FormattedMessage>
                        ),
                        key: 'id',
                        render: (text: string, record) => (
                            <>
                                {
                                    record.release_info[
                                        customFormat('item.name', intl)
                                    ]
                                }
                            </>
                        ),
                    },
                    {
                        title: (
                            <FormattedMessage id="到达地"></FormattedMessage>
                        ),
                        key: 'id',
                        render: (text: string, record) => (
                            <>
                                {(record?.release_info?.reach_city &&
                                    record?.release_info?.reach_city[
                                        customFormat(
                                            'item.city.mergename',
                                            intl,
                                        )
                                    ]) ||
                                    customFormat('不限', intl)}
                            </>
                        ),
                    },
                    {
                        title: <FormattedMessage id="数量"></FormattedMessage>,
                        key: 'id',
                        render: (text: string, record) => (
                            <>
                                {record.release_info.goods_num}
                                {customFormat(
                                    record.release_info.price_unit,
                                    intl,
                                )}
                            </>
                        ),
                    },
                    {
                        title: (
                            <FormattedMessage id="期望价格"></FormattedMessage>
                        ),
                        key: 'id',
                        render: (text: string, record) => (
                            <>
                                {record.release_info.desire_price}
                                {customFormat(
                                    record.release_info.price_unit,
                                    intl,
                                )}
                            </>
                        ),
                    },
                    {
                        title: (
                            <FormattedMessage id="所属行业"></FormattedMessage>
                        ),
                        key: 'id',
                        render: () => (
                            <FormattedMessage id="货物竞标"></FormattedMessage>
                        ),
                    },
                    {
                        title: (
                            <FormattedMessage id="发布时间"></FormattedMessage>
                        ),
                        key: 'id',
                        render: (text: string, record) => (
                            <>
                                {dayjs(record.createtime * 1000).format(
                                    'YYYY-MM-DD HH:mm:ss',
                                )}
                            </>
                        ),
                    },
                    ...baseBtn,
                ]);
                /* 货物 */
                break;
            case 'transport':
                /* 运输 */
                setcolumns([
                    {
                        title: (
                            <FormattedMessage id="订单编号"></FormattedMessage>
                        ),
                        key: 'order_no',
                        render: (text: string, record) => (
                            <>{record.order_no}</>
                        ),
                    },
                    {
                        title: (
                            <FormattedMessage id="出发地"></FormattedMessage>
                        ),
                        key: 'id',
                        render: (text: string, record) => (
                            <>
                                {record.release_info.departure_city[
                                    customFormat('item.city.mergename', intl)
                                ] || customFormat('不限', intl)}
                            </>
                        ),
                    },
                    {
                        title: (
                            <FormattedMessage id="到达地"></FormattedMessage>
                        ),
                        key: 'id',
                        render: (text: string, record) => (
                            <>
                                {record.release_info.reach_city[
                                    customFormat('item.city.mergename', intl)
                                ] || customFormat('不限', intl)}
                            </>
                        ),
                    },
                    {
                        title: (
                            <FormattedMessage id="载重量"></FormattedMessage>
                        ),
                        key: 'id',
                        render: (text: string, record) => (
                            <>
                                {record.release_info[
                                    customFormat('item.load_num', intl)
                                ] || '-'}
                                kg
                            </>
                        ),
                    },
                    {
                        title: <FormattedMessage id="体积"></FormattedMessage>,
                        key: 'id',
                        render: (text: string, record) => (
                            <>
                                {record.release_info[
                                    customFormat('item.goods_volume', intl)
                                ] + 'm³'}
                            </>
                        ),
                    },
                    {
                        title: <FormattedMessage id="车型"></FormattedMessage>,
                        key: 'id',
                        render: (text: string, record) => (
                            <>
                                {
                                    record.release_info[
                                        customFormat(
                                            'item.car_category_name',
                                            intl,
                                        )
                                    ]
                                }
                            </>
                        ),
                    },
                    {
                        title: (
                            <FormattedMessage id="整车/散货"></FormattedMessage>
                        ),
                        key: 'id',
                        render: (text: string, record) => (
                            <>
                                {record.release_info.whole_diffuse &&
                                    record.release_info.whole_diffuse[
                                        customFormat('item.text', intl)
                                    ]}
                            </>
                        ),
                    },
                    {
                        title: (
                            <FormattedMessage id="发布时间"></FormattedMessage>
                        ),
                        key: 'id',
                        render: (text: string, record) => (
                            <>
                                {dayjs(record.createtime * 1000).format(
                                    'YYYY-MM-DD HH:mm:ss',
                                )}
                            </>
                        ),
                    },
                    ...baseBtn,
                ]);
                break;
            case 'crossborder':
                setcolumns([
                    {
                        title: (
                            <FormattedMessage id="订单编号"></FormattedMessage>
                        ),
                        key: 'order_no',
                        render: (text: string, record) => (
                            <>{record.order_no}</>
                        ),
                    },
                    {
                        title: (
                            <FormattedMessage id="货物名称"></FormattedMessage>
                        ),
                        key: 'id',
                        render: (text: string, record) => (
                            <>
                                {
                                    record.release_info[
                                        customFormat('item.goods_name', intl)
                                    ]
                                }
                            </>
                        ),
                    },
                    {
                        title: (
                            <FormattedMessage id="出发地"></FormattedMessage>
                        ),
                        key: 'id',
                        render: (text: string, record) => (
                            <>
                                {(record?.release_info?.departure_city &&
                                    record?.release_info?.departure_city[
                                        customFormat(
                                            'item.city.mergename',
                                            intl,
                                        )
                                    ]) ||
                                    customFormat('不限', intl)}
                            </>
                        ),
                    },
                    {
                        title: (
                            <FormattedMessage id="到达地"></FormattedMessage>
                        ),
                        key: 'id',
                        render: (text: string, record) => (
                            <>
                                {(record?.release_info?.reach_city &&
                                    record?.release_info?.reach_city[
                                        customFormat(
                                            'item.city.mergename',
                                            intl,
                                        )
                                    ]) ||
                                    customFormat('不限', intl)}
                            </>
                        ),
                    },
                    {
                        title: <FormattedMessage id="数量"></FormattedMessage>,
                        key: 'id',
                        render: (text: string, record) => (
                            <>
                                {record.release_info.goods_num}
                                {customFormat(
                                    record.release_info.number_unit,
                                    intl,
                                )}
                            </>
                        ),
                    },
                    {
                        title: (
                            <FormattedMessage id="发布时间"></FormattedMessage>
                        ),
                        key: 'id',
                        render: (text: string, record) => (
                            <>
                                {dayjs(record.createtime * 1000).format(
                                    'YYYY-MM-DD HH:mm:ss',
                                )}
                            </>
                        ),
                    },
                    ...baseBtn,
                ]);
                /* 跨境货代 */
                break;
            case 'professional':
                /* 专业代办 */
                setcolumns([
                    {
                        title: (
                            <FormattedMessage id="订单编号"></FormattedMessage>
                        ),
                        key: 'order_no',
                        render: (text: string, record) => (
                            <>{record.order_no}</>
                        ),
                    },
                    {
                        title: (
                            <FormattedMessage id="个人名称"></FormattedMessage>
                        ),
                        key: 'id',
                        render: (text: string, record) => (
                            <>
                                {
                                    record.release_info[
                                        customFormat('item.person_name', intl)
                                    ]
                                }
                            </>
                        ),
                    },
                    {
                        title: (
                            <FormattedMessage id="所在城市"></FormattedMessage>
                        ),
                        key: 'id',
                        render: (text: string, record) => (
                            <>
                                {record?.release_info?.person_city &&
                                    record?.release_info?.person_city[
                                        customFormat(
                                            'item.city.mergename',
                                            intl,
                                        )
                                    ]}
                            </>
                        ),
                    },
                    {
                        title: (
                            <FormattedMessage id="发布时间"></FormattedMessage>
                        ),
                        key: 'id',
                        render: (text: string, record) => (
                            <>
                                {dayjs(record.createtime * 1000).format(
                                    'YYYY-MM-DD HH:mm:ss',
                                )}
                            </>
                        ),
                    },
                ]);
                break;
        }
    }
    async function goodsList(params: any) {
        const qParams = {
            ...params,
        };
        await getOrderList({ ...qParams }).then((res) => {
            settableparams(params);
            setAllData(res.data);
            const data = res.data.filter(
                (item) => item.type === params.search1,
            );
            setdataSource(data);
            compCol();
        });
    }
    function onValuesChange(val) {
        if (val.search1) {
            compCol();
            const data = allData.filter((item) => item.type === val.search1);
            setdataSource(data);
        }
    }
    type IModalForm = {
        subType: string;
        type: string;
    };
    const [vipShow, setvipShow] = useState(false);
    function onFinishModal(val: IModalForm) {
        const params = { ...val };
        if (params.type === '1') {
            history.push(listUrl[params.subType], { type: '1' });
        } else {
            if (!initialState?.auth) {
                return;
            }
            if (initialState.auth.auth !== 'all') {
                if (
                    initialState.auth.release_num === 0 ||
                    initialState.auth.release_num < 1
                ) {
                    setvipShow(true);
                    // 弹出vip购买弹窗
                    return false;
                } else {
                    if (initialState.isAuthName?.status !== 2) {
                        authModal(
                            intl.formatMessage({ id: 'authText' }),
                            intl.formatMessage({ id: '立即认证' }),
                            intl.formatMessage({ id: '继续使用' }),
                        );
                        return;
                    }
                }
            }
            history.push(listUrl[params.subType], { type: '2' });
        }
    }
    const authShow = ['goods2', 'transport2', 'professional2', 'crossborder2'];
    const subData = useRef();
    const [subOptions, setsubOptions] = useState();
    const filterSubOptions = (type?: string) => {
        if (!subData.current) {
            return [];
        }
        if (type || formModal.getFieldValue('type') === '1') {
            setsubOptions(
                subData.current['1'].filter((item) => {
                    return ['library1', 'news1'].indexOf(item.auth) === -1;
                }),
            );
        } else {
            setsubOptions(
                subData.current['2'].filter((item) => {
                    return authShow.indexOf(item.auth) !== -1;
                }),
            );
        }
    };
    useEffect(() => {
        (async () => {
            setpageLoading(true);
            await goodsList({ ...tableparams });
            await getUserAuthIcon().then((res) => {
                subData.current = res.data;
                filterSubOptions('1');
            });
            setpageLoading(false);
        })();
    }, []);
    return (
        <Spin spinning={pageLoading}>
            <Form
                colon={false}
                form={form}
                onValuesChange={onValuesChange}
                onFinish={(params) =>
                    goodsList({
                        ...tableparams,
                        ...params,
                        page: 1,
                        size: 10,
                    })
                }
                autoComplete="off"
            >
                <Row gutter={15}>
                    <Col span={4}>
                        <Form.Item
                            initialValue={0}
                            label={
                                <FormattedMessage id="订单状态"></FormattedMessage>
                            }
                            name="status"
                        >
                            <Select options={currentOptions} />
                        </Form.Item>
                    </Col>
                    <Col span={4}>
                        <Form.Item
                            label={
                                <FormattedMessage id="行业"></FormattedMessage>
                            }
                            initialValue={'goods'}
                            name="search1"
                        >
                            <Select options={options1} />
                        </Form.Item>
                    </Col>
                    <Col span={4}>
                        <Form.Item
                            label={
                                <FormattedMessage id="发布时间"></FormattedMessage>
                            }
                            name="search"
                        >
                            <Select options={options2} />
                        </Form.Item>
                    </Col>
                    <Col span={4}>
                        <Form.Item>
                            <Space>
                                <Button htmlType="submit" type="primary">
                                    <FormattedMessage id="搜索"></FormattedMessage>
                                </Button>
                                <Button
                                    htmlType="reset"
                                    onClick={() => {
                                        goodsList({
                                            status: 0,
                                            search1: 'goods',
                                            page: 1,
                                            size: 10,
                                        });
                                    }}
                                >
                                    <FormattedMessage id="重置"></FormattedMessage>
                                </Button>
                                <Button
                                    onClick={() => {
                                        setIsModalOpen(true);
                                    }}
                                    type="primary"
                                    ghost
                                >
                                    <FormattedMessage id="发布"></FormattedMessage>
                                </Button>
                            </Space>
                        </Form.Item>
                    </Col>
                </Row>
            </Form>
            <Table dataSource={dataSource} rowKey="id" columns={columns} />
            <Modal
                title={intl.formatMessage({ id: '发布类型' })}
                open={isModalOpen}
                footer={null}
            >
                <Form
                    form={formModal}
                    layout="vertical"
                    onFinish={onFinishModal}
                    autoComplete="off"
                >
                    <Form.Item
                        name="type"
                        label={intl.formatMessage({ id: '发布类型' })}
                        rules={[{ required: true }]}
                        initialValue={'1'}
                    >
                        <Select
                            onChange={() => {
                                formModal.setFieldValue('subType', null);
                                filterSubOptions();
                            }}
                            options={[
                                {
                                    value: '1',
                                    label: intl.formatMessage({
                                        id: '商家推广发布',
                                    }),
                                },
                                {
                                    value: '2',
                                    label: intl.formatMessage({
                                        id: '竞标任务发布',
                                    }),
                                },
                            ]}
                        />
                    </Form.Item>
                    <Form.Item
                        name="subType"
                        label={intl.formatMessage({ id: '二级分类' })}
                        rules={[{ required: true }]}
                    >
                        <Select
                            fieldNames={{
                                label: intl.formatMessage({id: "item.title"}),
                                value: 'auth',
                            }}
                            options={subOptions}
                        />
                    </Form.Item>
                    <Form.Item style={{ textAlign: 'right' }}>
                        <Space>
                            <Button type="primary" htmlType="submit">
                                <FormattedMessage id="确认"></FormattedMessage>
                            </Button>
                            <Button
                                htmlType="button"
                                onClick={() => {
                                    setIsModalOpen(false);
                                }}
                            >
                                <FormattedMessage id="关闭"></FormattedMessage>
                            </Button>
                        </Space>
                    </Form.Item>
                </Form>
            </Modal>
            <VipPopup
                vipShow={vipShow}
                onChange={() => {
                    setvipShow(false);
                }}
            ></VipPopup>
        </Spin>
    );
};
export default Order;
